package com.zhentao.controller;

import com.zhentao.Exception.vo.ResultVo;
import com.zhentao.service.OrderService;
import com.zhentao.utils.JwtUtil;
import com.zhentao.vo.OrderCreateVO;
import com.zhentao.vo.OrderDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "订单接口")
@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final JwtUtil jwtUtil;
    private final HttpServletRequest request;

    private Long getUserId() {
        String token = request.getHeader("Authorization");
        System.err.println("token:" + token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        return jwtUtil.getUserIdFromToken(token);
    }

    @ApiOperation("创建订单")
    @PostMapping("/create")
    public ResultVo<String> createOrder(@RequestBody OrderCreateVO orderCreateVO) {
        System.err.println(getUserId());
        Long userId = getUserId();
        orderCreateVO.setUid(userId);
        String orderNo = orderService.createOrder(orderCreateVO);
        return ResultVo.success(orderNo);
    }

    @ApiOperation("获取订单详情")
    @GetMapping("/{orderNo}")
    public ResultVo<OrderDetailVO> getOrderDetail(@PathVariable String orderNo) {
        Long userId = getUserId();
        return ResultVo.success(orderService.getOrderDetail(userId, orderNo));
    }

    @ApiOperation("获取我的订单列表")
    @GetMapping("/list")
    public ResultVo<List<OrderDetailVO>> getMyOrders() {
        Long userId = getUserId();
        return ResultVo.success(orderService.getMyOrders(userId));
    }
    @ApiOperation("获取我的订单列表")
    @GetMapping("/list2")
    public ResultVo<List<OrderDetailVO>> getMyOrdersList2(Integer id) {
        return ResultVo.success(orderService.getMyOrders(Long.valueOf(id)));
    }

    @ApiOperation("取消订单")
    @PostMapping("/cancel/{orderNo}")
    public ResultVo<Void> cancelOrder(@PathVariable String orderNo) {
        Long userId = getUserId();
        orderService.cancelOrder(userId, orderNo);
        return ResultVo.success();
    }

    @ApiOperation("支付订单")
    @PostMapping("/pay/{orderNo}")
    public ResultVo<String> payOrder(@PathVariable String orderNo) {
        Long userId = getUserId();
        String payUrl = orderService.payOrder(userId, orderNo);
        return ResultVo.success(payUrl);
    }
}
